package com.dense.kuiniu.bookborrow.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.util.ScreenUtils;
import com.dense.kuiniu.bookborrow.R;

import androidx.annotation.NonNull;
import me.jessyan.autosize.AutoSizeCompat;

/**
 * @author zhangyu
 * @date 2020/4/8
 */
public abstract class DialogMeasure extends Dialog implements IMeasure {

    private static final float DEFAULT_WIDTH_PERCENT = 500f / 1280;
    private static final float DEFAULT_HEIGHT_PERCENT = 500f / 1024;

    protected abstract int layoutRes();

    protected abstract void init(Context context, View view);

    public DialogMeasure(Context context) {
        this(context, R.style.custom_dialog);
    }

    public DialogMeasure(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        final View view = LayoutInflater.from(context).inflate(layoutRes(), null);
        init(context, view);
        setContentView(view);
    }

    @Override
    public void show() {
        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            super.show();
            measureSize(dialogWindow);
            fullScreenImmersive(dialogWindow.getDecorView());
            dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        }
    }

    protected void measureSize(Window dialogWindow) {
        if (dialogWindow != null) {
            dialogWindow.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.shape_transparent));
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = (int) (ScreenUtils.getScreenWidth() * (widthPercent() == 0 ? DEFAULT_WIDTH_PERCENT : widthPercent())); // 宽度
            lp.height = (int) (ScreenUtils.getScreenHeight() * (heightPercent() == 0 ? DEFAULT_HEIGHT_PERCENT : heightPercent())); // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogWindow.setWindowAnimations(R.style.DialogOutAndInStyle);
        }
    }

    private void fullScreenImmersive(View view) {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        if (view != null) {
            view.setSystemUiVisibility(uiOptions);
        }
    }
}
